import React from 'react';
import moment from 'moment';
import Link from 'umi/link'

import { connect } from 'dva';

import { Card, Divider, Button, Table,Modal, DatePicker,Form } from 'antd';

import DescriptionList from '@/components/DescriptionList';
const { Description } = DescriptionList;

const FormItem = Form.Item;


const lineFormPath = '/AccountMove/AccountBalanceLineForm'

@connect(({
  accountBalance,
  accountBalanceLine,
  accountAccount,
  accountSubAccount
}) => ({
  accountBalance,
  accountBalanceLine,
  accountAccount,
  accountSubAccount
}))
class Profile extends React.Component {
  state = {
    visible: false,
    visibleDel: false,
    visibleEditDate: false,
    line_id: 0,
    checkMsg: '',
  }

  treeview = [
      {
        title: '',
        dataIndex: '_',
        render: (_, { id }) => {
          return <Link to={`${lineFormPath}?id=${id}`}>编辑</Link>;
        },
      },

    {
      title: '',
      dataIndex: '_2',
      render: (_, { id }) => (
        <Button onClick={() => this.showDel( id )}>删除</Button>
      ),
    },

      { title: '科目编码', dataIndex: 'account_id.code', },
      { title: '科目名称', dataIndex: 'account_id.name', },
      { title: '明细编码', dataIndex: 'sub_account_id.code', },
      { title: '明细科目', dataIndex: 'sub_account_id.name', },
      { title: '类型', dataIndex: 'type', },
      { title: '借方', dataIndex: 'debit', },
      { title: '贷方', dataIndex: 'credit', },
      { title: '数量', dataIndex: 'quantity', },
      { title: '价格', dataIndex: 'price', },
      { title: '到期', dataIndex: 'date_maturity', },
  ]

  id = 0

  async componentDidMount() {
    const { dispatch } = this.props;

    await dispatch({
        type: 'accountBalance/find_open',
        payload:  {}
    });

    const { accountBalance } = this.props;
    this.id = accountBalance.id

    const domain = [
      ['balance_id','=',this.id],
      ['type','=','open'],
    ]

    await dispatch({
        type: 'accountBalanceLine/search',
        payload:  {domain}
    });

  }



  showEditDate() {
    this.setState({
      visibleEditDate: true
    })

  }

  showDel(id) {


    this.setState({
      line_id: id,
      visibleDel: true
    })

  }


  checkBalance(){
    const { accountBalanceLine: { recordsList } } = this.props;

    const sum = recordsList.reduce((acc,cur)=>{
      acc += cur.balance
      return acc
    },0)

    this.setState({
        checkMsg: sum ? '不平衡!!!' : '平衡, ok',
    })


  }


  async handleOkDel(){
    const { line_id } = this.state

    if(line_id){
        const { dispatch } = this.props;

        await dispatch({
          type: 'accountBalance/write',
          payload:  {
            id: this.id,
            vals: {line_ids: [[2,line_id,0]] },
          }
        });

      const domain = [
        ['balance_id','=',this.id],
        ['type','=','open'],
      ]

      await dispatch({
        type: 'accountBalanceLine/search',
        payload:  {domain}
      });



      this.setState({
        line_id: 0,
      })

    }

    this.handleCancel()

  }




  handleOkEditDate(){
    const { form: { validateFields } } = this.props;
    validateFields( async  (err, values) => {
      if (!err) {

        const { date } = values

        const { dispatch } = this.props;

        await dispatch({
          type: 'accountBalance/write',
          payload:  {
            id: this.id,
            vals: {date: date.format('YYYY-MM-DD') },
          }
        });

        this.setState({
          visibleEditDate: false,
        })

      }
    });
  }

  handleCancel(){
    this.setState({
      visible: false,
      visibleDel: false,
      visibleEditDate: false,
    })
  }

  render() {
    const { form: { getFieldDecorator }  } = this.props;
    const { accountBalance: { record } } = this.props;
    const { accountBalanceLine: { recordsList } } = this.props;

    //console.log(record)

    //const { accountAccount: { recordsList: accountList } } = this.props;
    //const { accountSubAccount: { recordsList: subAccountList } } = this.props;

    const {  visibleDel,visibleEditDate,checkMsg } = this.state

    //const line_ids = record.line_ids || []
    //const line0 =  line_ids.filter(item=>item.id===line_id)
    //const lineRecord = line0.length > 0 ? line0[0] : {}


    const { accountBalance } = this.props;

    const balance_id = accountBalance.id



    return (
      <Card bordered={false}>
        <DescriptionList size="large" title='说明' style={{ marginBottom: 32 }}>
          <div>期初数录入后，必须验算平衡! </div>
        </DescriptionList>


        <DescriptionList size="large" title='基本信息' style={{ marginBottom: 32 }}>
          <Description term='日期' >{record.date}</Description>
        </DescriptionList>
        <Divider style={{ marginBottom: 32 }} />
        <DescriptionList size="large" title='操作控制' style={{ marginBottom: 32 }}>

          <Description >
            <Button onClick={()=>this.showEditDate()}>修改日期</Button>
          </Description>


          <Description >
            <Button>
              <Link to={`${lineFormPath}?balance_id=${balance_id}`}>新增</Link>
            </Button>
          </Description>

          <Description >
            <Button onClick={()=>this.checkBalance()}>试算平衡</Button>
            {checkMsg}
          </Description>

        </DescriptionList>

        <Modal title='修改日期'
          visible={visibleEditDate}
          onOk={()=>this.handleOkEditDate()}
          onCancel={()=>this.handleCancel()}
        >

          <Form>

            <FormItem label="日期">
              {getFieldDecorator('date', {
                rules: [{ required: true }],
                initialValue: record.date ? moment(record.date, 'YYYY-MM-DD') : moment()
               // initialValue: moment().format('YYYY-MM-DD')
               // initialValue: moment(record.date, 'YYYY-MM-DD'),
              })(<DatePicker />)}
            </FormItem>

          </Form>

        </Modal>


        <Modal title='删除'
          visible={visibleDel}
          onOk={()=>this.handleOkDel()}
          onCancel={()=>this.handleCancel()}
        >
         删除?

        </Modal>



        <Table columns={this.treeview} dataSource={recordsList} rowKey="id" />
      </Card>
    );
  }
}

export default Form.create()(Profile);

